<template>
  <div class="fieldManage zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">功能位置</p>
            <div class="ipt">
              <Cascader clearable :data="orgList" v-model="searchParams.factoryCode" change-on-select
                        placeholder="请选择"></Cascader>
            </div>
          </div>
        </Col>

        <Col span="4">
          <div>
            <p class="label">{{ $t('班次') }}</p>
            <div class="ipt">
              <Input type="text" v-model="searchParams.shift" :placeholder="`${$t('common.inputInfo')}`"></Input>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('是否为生产时间') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.timeFlag" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option value="是">{{ $t('common.Yes') }}</Option>
                <Option value="否">{{ $t('common.No') }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">状态</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.status"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option value="1">启用</Option>
                <Option value="0">禁用</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn" type="primary" @click="search()">
                {{ $t('common.Query') }}
              </Button>
              <Button class="reset-btn" @click="reset()">{{ $t('common.reset') }}</Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="showAddModal">{{ $t('common.New') }}</Button>
        <Button @click="importExcelShow">{{ $t('common.Import') }}</Button>
        <Button @click="exportTemplate">{{ $t('preliminary.DownloadTemplate') }}</Button>
        <Button @click="exportExcel">{{ $t('common.Export') }}</Button>
      </div>

      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            @on-column-width-resize="onColumnWidthResize"
            ellipsis
            ref="selection"
            :columns="tableColumns"
            :data="tableData"
            @on-selection-change="onSelectChange"
        >
          <template slot-scope="{ row }" slot="shiftStr">
            <span>{{ row.shiftStr + '（' + row.shiftStartTime + ' - ' + row.shiftEndTime + '）' }}</span>
          </template>
          <template slot-scope="{ row }" slot="status">
              <span>
                {{ row.status == 1 ? '启用' : '禁用' }}
              </span>
          </template>
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="updateStatus(row, row.status == 1 ? 0 : 1)"><i
                class="iconfont zy-common-bianji"></i>{{ row.status == 1 ? '禁用' : '启用' }}</span>
            <span class="operationBtn" @click="showAddModal(row)"><i
                class="iconfont zy-common-bianji"></i>{{ $t('common.Edit') }}</span>
            <span class="operationBtn" @click="(deleteModal = true), (deleteIds = [row.id])"
            ><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span
            >
          </template>
        </Table>
      </div>

      <div class="pageWrap mt16">
        <pageLeftTitle :total="pageHelper.total" :selected="tableDataIdList.length"/>
        <Page
            :total="pageHelper.total"
            :page-size="pageHelper.pageSize"
            :page-size-opts="pageSizeOption"
            :current="pageHelper.pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>
    <Modal :mask-closable="false" v-model="addModal" :title="addtitle" class="modal-content-layout">
      <Form ref="form" class="formList" :model="formItem" label-position="top" :rules="ruleValidate">
        <Row :gutter="20">
          <Col span="12">
            <FormItem label="功能位置" prop="factoryCode">
              <Cascader
                  clearable
                  ref="cascader"
                  :data="orgList"
                  v-model="formItem.factoryCode"
                  change-on-select
                  @on-change="change"
                  placeholder="请选择"
              >
              </Cascader>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="班组" prop="teamId">
              <Select v-model="formItem.teamId" clearable @on-change="getMoldInfoChange"
                      :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item, index) of teamList" :value="item.id" :key="index">{{ item.team }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="12">
            <FormItem label="班次" prop="shift">
              <Input type="text" v-model="formItem.shift" :placeholder="`${$t('common.inputInfo')}`"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="时间段属性" prop="periodProperties">
              <Input type="text" v-model="formItem.periodProperties" :placeholder="`${$t('common.inputInfo')}`"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="12">
            <FormItem label="班次开始时间" prop="shiftStartTime">
              <TimePicker
                  type="time"
                  :value="formItem.shiftStartTime"
                  @on-change="
									(val) => {
										formItem.shiftStartTime = val;
									}
								"
                  value-format="yyyy-MM-dd"
                  :placeholder="`${$t('common.selectInfo')}开始时间`"
              />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="班次结束时间" prop="shiftEndTime">
              <TimePicker
                  type="time"
                  :value="formItem.shiftEndTime"
                  @on-change="
									(val) => {
										formItem.shiftEndTime = val;
									}
								"
                  value-format="yyyy-MM-dd"
                  :placeholder="`${$t('common.selectInfo')}结束时间`"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="12">
            <FormItem label="是否为生产时间" prop="timeFlag">
              <Select v-model="formItem.timeFlag" clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option value="是">是</Option>
                <Option value="否">否</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="计划停机时长(分钟)" prop="planStopTime">
              <InputNumber
                  :min="0"
                  style="width: 218px"
                  :precision="0"
                  v-model="formItem.planStopTime"
                  :default-value="0"
                  placeholder="请输入停机时间"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="24">
            <FormItem label="备注" prop="remark">
              <Input type="text" maxlength="200" v-model="formItem.remark"
                     :placeholder="`${$t('common.inputInfo')}`"></Input>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="default" @click="addModal = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="loading" @click="addOk('form')">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="deleteModal" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.confirmDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteModal = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="handleDelete">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <importExcelModal :importExcelStateF="importExcelState" v-if="importExcelState"
                      @importExcelChange="importExcelChange"></importExcelModal>
  </div>
</template>

<script>
import {getCompany, findOrgByToken} from '@/api/index.js';
import recursion from '@/util/recursion';
import {queryPage, exportExcel, addApi, editApi, getTeamList} from '@/api/system/production-input/production-shift.js';
import fileDownload from 'js-file-download';
import importExcelModal from '@/components/importExcel.vue';
import toggleTableOperation from '@/mixins/toggleTableOperation';
import {updateStatusProductionShiftApi} from "@/api/spareParts/storeHouse";

export default {
  name: 'ProductionShift',
  mixins: [toggleTableOperation],
  components: {importExcelModal},
  data() {
    return {
      loading: false,
      searchParams: {},
      tableColumns: [
        {
          key: 'selection',
          type: 'selection',
          width: 60,
          align: 'center',
        },
        {
          title: '功能位置',
          key: 'factoryName',
          align: 'center',
          minWidth: 120,
          resizable: true,
        },
        {
          title: '班组',
          key: 'team',
          align: 'center',
          minWidth: 140,
          resizable: true,
        },
        {
          title: this.$t('班次'),
          key: 'shift',
          align: 'center',
          minWidth: 140,
          resizable: true,
        },
        {
          title: this.$t('开始时间'),
          key: 'shiftStartTime',
          align: 'center',
          minWidth: 190,
          resizable: true,
        },
        {
          title: this.$t('结束时间'),
          key: 'shiftEndTime',
          align: 'center',
          minWidth: 160,
          resizable: true,
        },
        {
          title: this.$t('总时长') + '(H)',
          key: 'shiftTotalHourTime',
          align: 'center',
          minWidth: 160,
          resizable: true,
        },
        {
          title: this.$t('时间段属性'),
          key: 'periodProperties',
          align: 'center',
          width: 110,
          resizable: true,
        },
        {
          title: '计划停机时长(分钟)',
          key: 'planStopTime',
          align: 'center',
          minWidth: 180,
          resizable: true,
        },
        {
          title: this.$t('是否为生产时间'),
          key: 'timeFlag',
          align: 'center',
          width: 170,
          resizable: true,
        },
        {
          title: "状态",
          slot: "status",
          minWidth: 100,
          align: "center",
          resizable: true
        },
        {
          title: '备注',
          key: 'remark',

          minWidth: 160,
          tooltip: true,
          resizable: true,
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: 'action',
          align: 'center',
          fixed: 'right',
          width: 280,
        },
      ],
      tableData: [],
      pageSizeOption: [10, 20, 30, 40],
      pageHelper: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
      deleteIds: [],
      deleteModal: false,
      productionShiftList: [
        {
          value: 0,
          name: '早班（8H）',
        },
        {
          value: 1,
          name: '中班（8H）',
        },
        {
          value: 2,
          name: '白班（12H）',
        },
        {
          value: 3,
          name: '常白班（8H）',
        },
        {
          value: 4,
          name: '夜班（12H）',
        },
      ],
      ruleValidate: {
        planStopTime: [
          {
            required: true,
            message: '请输入非负整数（单位：分钟）',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              // 允许 0 或正整数
              if (value === null || value === undefined || value === '') {
                return callback(new Error('不能为空'));
              }
              if (!/^(0|[1-9]\d*)$/.test(value)) {
                return callback(new Error('必须为非负整数（如 0、1、2）'));
              }
              callback();
            }
          }
        ],
        shiftStartTime: [{required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change'}],
        shiftEndTime: [{required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change'}],
        // time: [{ required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change', type: 'array' }],
        shift: [{required: true, message: `${this.$t('common.inputInfo')}`, trigger: 'blur'}],
        // team: [{ required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change' }],
        timeFlag: [{required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change'}],
        factoryCode: [{required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change', type: 'array'}],
      },
      checkBtnPermission: {},
      companyList: [],
      factoryList: [],
      tableDataIdList: [],
      addModal: false,
      formItem: {},
      importExcelState: false,
      orgList: [],
      teamList: [],
    };
  },
  methods: {
    // 更新状态
    updateStatus(row, status) {
      console.log(111)
      updateStatusProductionShiftApi({
        id: row.id,
        status: status
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(status === 1 ? '启用成功' : '禁用成功');
          this.searchList();
        } else {
          this.$Message.error(status === 1 ? '启用失败' : '禁用失败');
        }
      }).catch(() => {
      });
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    search() {
      if (this.searchParams.factoryCode && this.searchParams.factoryCode.length !== 0) {
        this.searchParams.factoryCode = [this.searchParams.factoryCode[this.searchParams.factoryCode.length - 1]];
      }
      this.changeNum();
    },
    changeNum() {
      this.pageHelper.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageHelper.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageHelper.pageNum = val;
      this.searchList();
    },
    searchList() {
      //查询列表
      let params = {
        pageNum: this.pageHelper.pageNum,
        pageSize: this.pageHelper.pageSize,
        ...this.searchParams,
      };

      queryPage(params).then((res) => {
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.pageHelper.total = res.data.total;
        } else {
          this.$Message.warning({content: res.msg, duration: 6, closable: true});
        }
      });
    },
    handleDelete() {
      this.axios({
        method: 'delete',
        url: '/dms/productionShift/delete',
        data: this.deleteIds,
      }).then((res) => {
        if (res.code == 200) {
          this.changeNum();
          this.deleteModal = false;
          this.$Message.success({content: res.msg, duration: 6, closable: true});
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    getMoldInfoChange(val) {
      const res = this.teamList.find((item) => item.id === val);
      this.$set(this.formItem, 'team', res.team);
    },
    onSelectChange(selection) {
      this.tableDataIdList = selection.map((item) => item.id);
    },
    //获取公司
    getCompanyList() {
      getCompany().then((res) => {
        if (res.code === 200) {
          this.companyList = res.data;
        } else {
          this.companyList = [];
          this.$Message.warning({content: res.msg, duration: 6, closable: true});
        }
      });
    },
    //功能位置
    getOrgList() {
      let params = {
        level: 0,
      };
      findOrgByToken(params).then((res) => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children',
          };
          this.orgList = recursion.convertTree(res.data, obj);
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    getTeam() {
      this.axios({
        method: 'get',
        url: '/dms/productionShift/getTeamList',
        params: {},
      }).then((res) => {
        if (res.code === 200) {
          this.teamList = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    addOk(name) {
      this.$refs[name].validate((valid) => {
        if (!valid) {
          return;
        } else {
          this.loading = true;
          if (this.formItem.id) {
            editApi(this.formItem).then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.searchList();
                this.$Message.success('编辑成功');
                this.addModal = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true,
                });
              }
            });
          } else {
            addApi(this.formItem).then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.searchList();
                this.$Message.success('新增成功');
                this.addModal = false;
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true,
                });
              }
            });
          }
        }
      });
    },
    async showAddModal(row) {
      if (row.id) {
        this.addtitle = `${this.$t('common.Edit')}`;
        this.formItem = {
          ...row,
        };
      } else {
        this.addtitle = `${this.$t('common.New')}`;
        this.formItem = {
          shiftStartTime: '',
          shiftEndTime: '',
          planStopTime: 0,
        };
        this.deviceList2 = [];
        this.$nextTick(() => {
          this.$refs.form.resetFields(); // 确保表单重置
        });
      }
      this.addModal = true;
    },
    // 导出
    exportExcel() {
      // let params = {
      //     ...this.searchParams,
      //     ids: this.tableDataIdList
      // }
      exportExcel().then((res) => {
        fileDownload(res, '生产班次.xlsx');
      });
    },
    //下载模板
    exportTemplate() {
      const filName = `${this.$t('班次导入模版')}`;
      this.axios({
        method: 'get',
        url: '/dms/productionShift/downloadTemplate',
        responseType: 'blob',
      }).then((res) => {
        fileDownload(res, filName + '.xlsx');
      });
    },
    //导出
    exportTemplateClick() {
      // let params = {
      //     belongCompanyId: this.searchParams.belongCompanyId,
      //     orgId: this.searchParams.orgId,
      //     deviceNo: this.searchParams.deviceNo,
      //     deviceName: this.searchParams.deviceName,
      //     ids: this.deleteIds,
      // };
      const filName = this.$t('生产班次');
      this.axios({
        method: 'post',
        url: '/dms/productionShift/exportTz',
        responseType: 'blob',
        // data: params,
      }).then((res) => {
        fileDownload(res, filName + '.xlsx');
      });
    },
    /*导入*/
    importExcelShow() {
      this.importExcelState = true;
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === 'success') {
        // this.$Message.success("导入成功");
        this.changeNum();
      }
    },
  },
  mounted() {
    this.searchList();
    this.getCompanyList();
    this.getOrgList();
    this.getTeam();
  },
  created() {
    this.getColumnWidth(this.tableColumns);
    let itemList = JSON.parse(window.localStorage.getItem('USER_URI'));
    for (let item of itemList) {
      if (item.code === 'ProductionShiftSearch') {
        this.checkBtnPermission.ProductionShiftSearch = true;
      }
      if (item.code === 'ProductionShiftExport') {
        this.checkBtnPermission.ProductionShiftExport = true;
      }
    }
  },
};
</script>

<style scoped lang="scss">
.fieldManage {
  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;
    }
  }
}
</style>

<style lang="scss"></style>
